use std::ptr::copy_nonoverlapping;

pub fn new_bytes(len: usize) -> Box<[u8]> {
    let mut buf = Vec::with_capacity(len);
    unsafe {
        buf.set_len(len);
    }
    buf.into_boxed_slice()
}

#[inline]
pub fn get_mut<T>(value: &T) -> &mut T {
    unsafe { &mut (*((value as *const T) as *mut T)) }
}

#[inline]
pub fn copy(dst: &mut [u8], src: &[u8]) {
    unsafe {
        copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len());
    }
}

#[inline]
pub fn encode_u8(buf: &mut [u8], value: u8) {
    buf[0] = value;
}

pub fn encode_u16(buf: &mut [u8], value: u16) {
    buf[0] = (value >> 8) as u8;
    buf[1] = value as u8;
}

pub fn encode_u32(buf: &mut [u8], value: u32) {
    buf[0] = (value >> 24) as u8;
    buf[1] = (value >> 16) as u8;
    buf[2] = (value >> 8) as u8;
    buf[3] = value as u8;
}

pub fn print_buf(tag: &str, buf: &[u8]) {
    print!("{}:", tag);
    for v in buf {
        print!("{:02x} ", v);
    }
    println!();
}

#[tauri::command]
pub fn md5_sum(buf: Box<[u8]>) -> [u8; 16] {
    md5::compute(&buf).0
}
